<template lang="pug">
  div(v-bind:class="['kalix-message',`kalix-message--${ type }`]"
  v-show="visible"
  @mouseenter="clearTimer"
  @mouseleave="startTimer"
  role="alert")
    div {{ message }}
</template>

<script type="text/babel">
  const typeMap = {
    success: 'success',
    info: 'info',
    warning: 'warning',
    error: 'error'
  }

  export default {
    data() {
      return {
        visible: false,
        message: '',
        duration: 3000,
        type: 'info',
        iconClass: '',
        customClass: '',
        onClose: null,
        showClose: false,
        closed: false,
        timer: null,
        dangerouslyUseHTMLString: false,
        center: false
      }
    },

    computed: {
      typeClass() {
        return this.type && !this.iconClass
          ? `el-message__icon el-icon-${typeMap[this.type]}`
          : ''
      }
    },

    watch: {
      closed(newVal) {
        if (newVal) {
          this.visible = false
          this.destroyElement()
        }
      }
    },

    methods: {
      destroyElement() {
        this.$destroy(true)
        this.$el.parentNode.removeChild(this.$el)
      },

      close() {
        this.closed = true
        if (typeof this.onClose === 'function') {
          this.onClose(this)
        }
      },

      clearTimer() {
        clearTimeout(this.timer)
      },

      startTimer() {
        if (this.duration > 0) {
          this.timer = setTimeout(() => {
            if (!this.closed) {
              this.close()
            }
          }, this.duration)
        }
      },
      keydown(e) {
        if (e.keyCode === 27) { // esc关闭消息
          if (!this.closed) {
            this.close()
          }
        }
      }
    },
    mounted() {
      this.startTimer()
      document.addEventListener('keydown', this.keydown)
    },
    beforeDestroy() {
      console.log('beforeDestroy')
      document.removeEventListener('keydown', this.keydown)
    }
  }
</script>
